﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;

namespace heyirunde
{
    public class DBHelper
    {
        public DBHelper() { }
        public static string connectionString = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
        /// <summary>
        /// 执行一条SQL语句 返回 DataTable
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(string text)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            conn.Open();

            SqlDataAdapter odda = new SqlDataAdapter(text, conn);

            DataSet ds = new DataSet();
            odda.Fill(ds);
            conn.Close();
            return ds.Tables[0];
        }
        #region - 带参数的SQL语句
        /// <summary>
        /// 读取DataTable数据
        /// </summary>
        /// <param name="text">sql语句，（带参数的完整的select语句，参数自定义）</param>
        /// <param name="param">参数数组，必须与sql参数相对应</param>
        /// <returns></returns>
        public static DataTable GetDataTable(string text, params SqlParameter[] param)
        {
            SqlConnection conne = new SqlConnection(connectionString);
            SqlDataAdapter odda = new SqlDataAdapter(text, conne);
            conne.Open();
            if (param != null)
                odda.SelectCommand.Parameters.AddRange(param);
            DataSet ds = new DataSet();
            odda.Fill(ds);
            odda.SelectCommand.Dispose();

            conne.Close();
            conne.Dispose();
            return ds.Tables[0];
        }

        /// <summary>
        /// 读取DataTable数据
        /// </summary>
        /// <param name="text">sql语句，（带参数的完整的select语句，参数必须从@0,开始）</param>
        /// <param name="param">参数数组</param>
        /// <returns></returns>
        public static DataTable GetDataTable(string text, params object[] param)
        {
            SqlConnection conne = new SqlConnection(connectionString);
            using (SqlDataAdapter odda = new SqlDataAdapter(text, conne))
            {
                if (conne.State != ConnectionState.Open)
                    conne.Open();
                try
                {
                    if (param != null)
                    {
                        for (int i = 0; i < param.Length; i++)
                        {
                            SqlParameter sp = new SqlParameter("@" + i.ToString(), param[i]);
                            odda.SelectCommand.Parameters.Add(sp);
                        }
                    }
                    DataSet ds = new DataSet();
                    odda.Fill(ds);
                    return ds.Tables[0];
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
                finally
                {
                    if (conne.State != ConnectionState.Closed)
                        conne.Close();
                }
            }
        }

        /// <summary>
        /// 返回会受影响行数
        /// </summary>
        /// <param name="cmdText">T-SQL命令（update,insert,delete语句）</param>
        /// <param name="param">参数列表（可为空null）</param>
        /// <returns></returns>
        //public static int ExecuteCommand(string cmdText, params SqlParameter[] param)
        //{
        //    SqlConnection conne = new SqlConnection(connectionString);
        //    SqlCommand cmd = new SqlCommand(cmdText, conne);
        //    if (param != null)
        //        cmd.Parameters.AddRange(param);
        //    if (conne.State != ConnectionState.Open)
        //        conne.Open();
        //    int j = cmd.ExecuteNonQuery();
        //    if (conne.State != ConnectionState.Closed)
        //        conne.Close();
        //    return j;
        //}
        /*********************
         * 调用示例：
         *  CarDBHelper.ExecuteCommand("insert into Log ([UserId] ,[TableName],[LogState],[PKID],[CreateTime]) values (@userId,@TableName,@LogState,@PKID,@CreateTime)",
         *  new SqlParameter[]{
         *      new SqlParameter("@userId",userId),
         *      new SqlParameter("@TableName",TableName),
         *      new SqlParameter("@LogState",LogState),
         *      new SqlParameter("@PKID",PKID),
         *      new SqlParameter("@CreateTime",CreateTime),
         *  });
         * 调用示例：
         * CarDBHelper.ExecuteCommand("insert into Log ([UserId] ,[TableName],[LogState],[PKID],[CreateTime]) values (@userId,@TableName,@LogState,@PKID,@CreateTime)",
         * new SqlParameter("@userId", "6"),
         * new SqlParameter("@TableName", "Administrator"),
         * new SqlParameter("@LogState", "登录"),
         * new SqlParameter("@PKID", "7"),
         * new SqlParameter("@CreateTime", "2013-03-11"));
         *********************/

        /// <summary>
        /// 返回会受影响行数
        /// </summary>
        /// <param name="cmdText">T-SQL命令（update,insert,delete语句）</param>
        /// <param name="param">参数列表（可为空null）</param>
        /// <returns></returns>
        public static int ExecuteCommand(string cmdText, params object[] param)
        {
            SqlConnection conne = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(cmdText, conne);
            if (param != null)
            {
                for (int i = 0; i < param.Length; i++)
                {
                    SqlParameter sp = new SqlParameter("@" + i.ToString(), param[i]);
                    cmd.Parameters.Add(sp);
                }
            }
            if (conne.State != ConnectionState.Open)
            {
                conne.Open();
            }
            int j = cmd.ExecuteNonQuery();
            if (conne.State != ConnectionState.Closed)
                conne.Close();
            return j;
        }
        /*******************
         * 调用示例：
         *  CarDBHelper.GetDataTable(
         *  "insert into Log ([UserId] ,[TableName],[LogState],[PKID],[CreateTime]) values (@0,@1,@2,@3,@4)",
         *  "6","Administrator","登录","7","2013-03-11");
         *******************/

        #endregion

        /// <summary>
        /// 执行一条SQL语句 返回 DataTable
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        //public static DataTable GetDataTable(string text, SqlParameter[] parms)
        //{
        //    SqlConnection conn = new SqlConnection(connectionString);
        //    conn.Open();

        //    SqlDataAdapter odda = new SqlDataAdapter(text, conn);
        //    if (parms != null && parms.Length > 0)
        //    {
        //        odda.SelectCommand.Parameters.AddRange(parms);
        //    }
        //    DataSet ds = new DataSet();
        //    odda.Fill(ds);
        //    if (parms != null && parms.Length > 0)
        //    {
        //        odda.SelectCommand.Parameters.Clear();
        //    }
        //    conn.Close();
        //    return ds.Tables[0];
        //}
        /// <summary>
        /// 执行一条SQL语句 返回影响行数
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static int ExecuteCommand(string text)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            conn.Open();
            SqlCommand cmd = new SqlCommand(text, conn);
            int i = cmd.ExecuteNonQuery();
            conn.Close();
            return i;
        }

        /// <summary>
        /// 执行一条SQL语句 返回影响行数
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static int ExecuteCommand(string text, SqlParameter[] parms)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            conn.Open();
            SqlCommand cmd = new SqlCommand(text, conn);
            if (parms != null && parms.Length > 0)
            {
                cmd.Parameters.AddRange(parms);
            }
            int i = cmd.ExecuteNonQuery();
            if (parms != null && parms.Length > 0)
            {
                cmd.Parameters.Clear();
            }
            conn.Close();
            return i;
        }

        public static int ExecuteQuery(CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, conn, (SqlTransaction)null, commandType, commandText, commandParameters);
            int i = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            conn.Close();
            return i;
        }


        #region - 公共方法
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        /// <param name="tableName">表</param>
        /// <param name="strWhere">查询条件</param>
        /// <param name="orderby">排序方式</param>
        /// <param name="startIndex">起始索引</param>
        /// <param name="endIndex">结束索引</param>
        /// <returns>返回表的总记录数</returns>
        public static DataTable GetListByPage(string tableName, string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            { strSql.Append("order by T." + orderby); }
            else
            { strSql.Append("order by T.ID desc"); }
            strSql.Append(")AS Row, T.*  from [" + tableName + "] T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            { strSql.Append(" WHERE " + strWhere); }
            strSql.Append(" ) TT");
            if (startIndex <= endIndex)
                strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            else
                strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", endIndex, startIndex);
            return Query(strSql.ToString());
        }

        /// <summary>
        /// 执行SQL查询语句
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static DataTable Query(string text)
        {
            SqlConnection conne = new SqlConnection(connectionString);
            if (conne.State != ConnectionState.Open)
                conne.Open();
            SqlDataAdapter odda = new SqlDataAdapter(text, conne);
            DataSet ds = new DataSet();
            odda.Fill(ds);
            if (conne.State != ConnectionState.Open)
                conne.Close();
            return ds.Tables[0];
        }
        /// <summary>
        /// 获取记录总数
        /// </summary>
        /// <param name="strWhere">表</param>
        /// <returns>返回表的总记录数</returns>
        public static int GetRecordCount(string tableName, string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM [" + tableName + "] ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            object obj = GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        /// <param name="strWhere">表</param>
        /// <returns>返回表的总记录数</returns>
        public static int GetRecordCount(string tableName, string strWhere, SqlParameter[] parms)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM [" + tableName + "] ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            object obj = GetSingle(strSql.ToString(), parms);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        #endregion

        private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters)
        {
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
            command.Connection = connection;
            command.CommandText = commandText;
            if (transaction != null)
            {
                command.Transaction = transaction;
            }
            command.CommandType = commandType;
            if (commandParameters != null)
            {
                AttachParameters(command, commandParameters);
            }
            return;
        }

        private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
        {
            foreach (SqlParameter p in commandParameters)
            {
                if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
                {
                    p.Value = DBNull.Value;
                }
                command.Parameters.Add(p);
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.Fill(dataSet, tableName);
                connection.Close();
                return dataSet;
            }
        }

        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
                        parameter.Value = DBNull.Value;
                    command.Parameters.Add(parameter);
                }
            }
            return command;
        }

        #region - 私有方法
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (SqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }
        #endregion

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>		
        public static int ExecuteSqlTran(List<String> SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>		
        public static int ExecuteSqlTran(string strSql)
        {
            int rtn = 0;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    SqlTransaction st = conn.BeginTransaction();
                    cmd.Transaction = st;
                    try
                    {
                        cmd.CommandText = strSql.ToString();
                        rtn = cmd.ExecuteNonQuery();
                        st.Commit();
                    }
                    catch
                    {
                        st.Rollback();
                        return rtn;
                    }
                }

            }
            return rtn;
        }



        /// <summary>
        /// 执行SQL语句，可用作绑定DropdownList
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="objs"></param>
        /// <returns></returns>
        public static DataSet GetDropDownListSource(string sql, params object[] objs)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            conn.Open();
            SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
            if (objs != null)
            {
                for (int i = 0; i < objs.Length; i++)
                {
                    sda.SelectCommand.Parameters.AddWithValue("@" + i, objs[i]);
                }
            }

            DataSet dt = new DataSet();
            sda.Fill(dt);
            conn.Close();
            return dt;

        }
        public static DataSet GetUserInfo(string sql, params object[] objs)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            conn.Open();
            SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
            if (objs != null || objs.Length > 0)
            {
                for (int i = 0; i < objs.Length; i++)
                {
                    sda.SelectCommand.Parameters.AddWithValue("@" + i, objs[i]);
                }

            }

            DataSet ds = new DataSet();
            sda.Fill(ds);
            conn.Close();
            return ds;
        }

        /// <summary>
        /// 非查询语句
        /// </summary>
        /// <param name="cmdtype">命令类型，如果值为0代表存过名，值为1代表普通的sql语句</param>
        /// <param name="sqlstr">命令对象文本</param>
        /// <param name="objs">语句中的参数</param>
        /// <returns></returns>
        public static int ExecNoneQuery(int cmdtype, string sqlstr, params object[] objs)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(sqlstr, conn);
            if (cmdtype == 0)
            {
                cmd.CommandType = CommandType.StoredProcedure;
            }
            else
            {
                cmd.CommandType = CommandType.Text;
            }

            if (objs != null)
            {
                for (int i = 0; i < objs.Length; i++)
                {
                    cmd.Parameters.AddWithValue("@" + i, objs[i]);
                }
            }
            conn.Open();
            int result = cmd.ExecuteNonQuery();
            conn.Close();
            return result;
        }
    }
}